package com.utils.wifi

import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSpecifier
import android.os.Build
import android.provider.Settings

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 2021/6/17
 */
@TargetApi(Build.VERSION_CODES.Q)
class WifiImpl29: IWifi {
    override fun openWifi(context: Context) {
        context.startActivity(Intent(Settings.Panel.ACTION_WIFI))
    }

    override fun connectWifi(context: Context, ssid: String, pwd: String) {
        val specifier = WifiNetworkSpecifier.Builder().apply {
            setSsid(ssid)
            setWpa2Passphrase(pwd)
        }.build()

        val request = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .setNetworkSpecifier(specifier)
                .build()

        val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        connectivityManager.requestNetwork(request, object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                WifiUtils.wifiStateCallBack?.get()?.onConnected()
            }

            override fun onUnavailable() {
                super.onUnavailable()
                WifiUtils.wifiStateCallBack?.get()?.onConnectedFail()
            }
        })
    }

    override fun registerWifiStateChangerReceiver(context: Context, receiver: WifiConnectReceiver, wifiStateCallBack: WifiStateCallBack) {
        val intentFilter = IntentFilter()
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
        context.registerReceiver(receiver, intentFilter)
    }

    override fun unregisterWifiStateChangeReceiver(context: Context, receiver: WifiConnectReceiver?) {
        //nothing to do
    }
}